<template>
  <div class="app-container">
    <el-form autoComplete="on" ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="用户名">
        {{username}}
      </el-form-item>
      <el-form-item label="手机号">
        {{mobile}}
      </el-form-item>
      <el-form-item label="邮箱">
        {{mail}}
      </el-form-item>
      <el-form-item label="原密码" prop="old">
        <el-input type="old" v-model="form.old" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input type="password" v-model="form.password" size="18" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="password2">
        <el-input type="password" v-model="form.password2" size="18" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { passwd } from '@/api/account'

export default {
  data() {
    const validatePass = (rule, value, callback) => {
      if (this.error && this.error.param === 'old') {
        callback(new Error(this.error.message || '服务器错误'))
        delete this.error
        return
      }
      if (value.length < 5) {
        callback(new Error('密码不能小于5位'))
      } else {
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value !== this.form.password) {
        callback(new Error('确认密码不一致'))
      } else {
        callback()
      }
    }
    return {
      form: {
        old: '',
        password: '',
        password2: ''
      },
      rules: {
        old: [{ required: true, trigger: 'blur', validator: validatePass }],
        password: [{ required: true, trigger: 'blur', validator: validatePass }],
        password2: [{ required: true, trigger: 'blur', validator: validatePass2 }]
      }
    }
  },
  computed: {
    ...mapGetters([
      'avatar',
      'username',
      'mobile',
      'mail'
    ])
  },
  created() {
  },
  methods: {
    onSubmit() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          console.log('error submit!!')
          return false
        }
        passwd(this.form).then(res => {
          this.$message({
            type: 'success',
            message: '更新成功!'
          })
        }).catch(err => {
          this.error = err.error
          this.$refs.form.validate()
        })
      })
    },
    onCancel() {
      this.$message({
        message: '已取消添加!',
        type: 'warning'
      })
    }
  }
}
</script>

<style scoped>
.line{
  text-align: center;
}
</style>
